import { FIRST_READ, TypeConstants } from '../TypeConstants';
import { ReaderIn } from '../ReaderIn';
import { ITypeAdapter } from './ITypeAdapter';
import { WriterOut } from '../WriterOut';
import { DlJson } from '../DlJson';

export class ArrayTypeAdapter implements ITypeAdapter {
  write(writerOut: WriterOut): WriterOut {
    writerOut.setWriteValue(writerOut.getTarget())
    return writerOut
  }

  typeConstants(): TypeConstants {
    return TypeConstants.TYPE_ARRAY
  }

  read(readerIn: ReaderIn): ReaderIn {
    let targetArray = readerIn.getTarget() as Array<ESObject>
    let jsonArray = readerIn.getJson() as Array<ESObject>
    let defaultT
    if (readerIn.getReadNums() == FIRST_READ) {
      if (targetArray.length < 1) {
        throw Error("FIRST_READ==1 必须传大于一条的数组序列")
      }
      defaultT = targetArray[0]
      targetArray.splice(0, targetArray.length)
    } else {
      defaultT = readerIn.getDefault()
    }
    if ((defaultT != null && defaultT instanceof DlJson)) {
      //开始写入
      jsonArray?.forEach((jsonValue: ESObject) => {
        let targetSource = defaultT.createNew()
        let copyType = readerIn.getTypeFactory().create(targetSource)
        let copyReader = new ReaderIn(jsonValue, targetSource, readerIn.getTypeFactory(),readerIn.getReadNums())
        targetArray.push(copyType.read(copyReader).value())
      })
      readerIn.setValue(targetArray)
    } else {
      //目标对象数组没有默认值则直接返回
      if (jsonArray === null) {
        readerIn.setValue(targetArray)
      } else {
        readerIn.setValue(jsonArray)
      }
    }
    return readerIn
  }
}